package com.jkd.server.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class MyDecoder extends ByteToMessageDecoder {

    private StringBuilder str = new StringBuilder();

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        String HEXES = "0123456789ABCDEF";
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        final StringBuilder hex = new StringBuilder(2 * req.length);
        for (int i = 0; i < req.length; i++) {
            byte b = req[i];
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                    .append(HEXES.charAt((b & 0x0F)));
        }
        String string = hex.toString();
        str.append(string);
        //心跳
        String string1 = str.toString();
        boolean heartIs = string1.contains("4554554E47");
        boolean ybsz = string1.trim().endsWith("21") || (string1.startsWith("24") && string1.replaceAll(" ", "").length() == 26);
        if (heartIs || ybsz) {
            list.add(string1);
            str = new StringBuilder();
        }
        if (str.length() > 2000) {
            System.out.println("未识别的字节序列================》"+str);
            str = new StringBuilder();
        }
    }
}
